import pgzrun
import time
WIDTH=1000
HEIGHT=750

IMAGE_SIZE = 40

# velocity 速度 velocity = speed * dir
# speed    速率 只有大小没有方向

BACK_COLOR=(30,30,30)

class SnakeNode:
    def __init__(self):
        self.speed = IMAGE_SIZE * 3
        self.dir = (1, 0)
    
    def CreateNode(self, name, x, y):
        self.node = Actor(name, (x, y))
    
    def MoveToTarget(self, target):
        animate(self.node, pos = (target[0], target[1]), duration=IMAGE_SIZE / self.speed, on_finished = self.KeepMoving)
    
    def KeepMoving(self):
        pos = self.node.pos
        tx = pos[0] + self.dir[0] * IMAGE_SIZE
        ty = pos[1] + self.dir[1] * IMAGE_SIZE
        self.MoveToTarget((tx, ty))

    def UpdateDir(self, newDir):
        self.dir = newDir
        self.KeepMoving()

    def CheckOutOfMap(self):
        pos = self.node.pos
        if(pos[0] > WIDTH - IMAGE_SIZE // 2 or \
            pos[0] < IMAGE_SIZE // 2 or \
                pos[1] > HEIGHT - IMAGE_SIZE // 2 or \
                     pos[1] < IMAGE_SIZE // 2):
            time.sleep(0.5)
            self.node.pos = WIDTH // 2, HEIGHT // 2
            self.dir = (1, 0)
            self.KeepMoving()

    def RenderNode(self):
        self.node.draw()

node = SnakeNode()
node.CreateNode("bg", WIDTH // 2, HEIGHT // 2)
node.KeepMoving()

def on_key_down(key):
    global node
    if key==keys.UP:
        dir = (0, -1)
        node.UpdateDir(dir)
    if key==keys.DOWN:
        dir = (0, 1)
        node.UpdateDir(dir)
    if key==keys.LEFT:
        dir = (-1, 0)
        node.UpdateDir(dir)
    if key==keys.RIGHT:
        dir = (1, 0)
        node.UpdateDir(dir)

def update():
    global node
    node.CheckOutOfMap()

def draw():
    global node
    screen.clear()
    screen.fill(BACK_COLOR)
    node.RenderNode()

pgzrun.go()